import requests
import json
from tkinter import *
import os


'''
此模块提供ip地址归属查询功能
'''

class ipchecktest():
    def __init__(self):
        pass

    def windowsthree(self,root):
        w = Toplevel(root)
        w.title('ip地址归属查询')
        w.geometry('400x200')
        w.geometry('+600+400')
        w.maxsize(width='400',height='200')

        #标签页，用于注释说明
        l1 = Label(w,text='ip地址归属地查询，请确保网络正常',font='2')
        l1.grid(row=1,column=1,padx=5,pady=5)

        l2 = Label(w,text='目标ip',font='5',bg='yellow')
        l2.grid(row=2,column=0,padx=5,pady=5)

        l3 = Label(w,text='结果',font='5',bg='yellow')
        l3.grid(row=3,column=0,padx=5,pady=5)

        #输入框
        self.e1 = Entry(w)
        self.e1.grid(row=2,column=1,padx=5,pady=5)

        #开始按键
        b1 = Button(w,text='开始',font='5',bg='red',command=three.getresult)
        b1.grid(row=2,column=2,padx=5,pady=5)

        #输出框
        self.var=StringVar()
        self.e2 = Entry(w,textvariable=self.var)
        self.e2.grid(row=3,column=1,padx=5,pady=5)

        #退出按键
        # b2 = Button(w,text='退出',font='5',bg='red',command=quit)
        # b2.grid(row=3,column=2,padx=5,pady=5)

        w.mainloop()

    def getresult(self):
        #得到输入框中输入的值
        self.ipadd = self.e1.get()
        self.api='https://open.onebox.so.com/dataApi?callback=jQuery183039083655956956864_1562117373170&type=ip&src=onebox&tpl=0&num=1&query=ip&ip=%s&url=ip&_=1562119610793'%self.ipadd
        self.response1 = requests.get(self.api)
        self.response = self.response1.content.decode('utf-8')
        self.filters = re.findall(r'\((.*?)\)',self.response)[0]
        self.getjs = json.loads(self.filters)
        print(self.getjs)
        if '1' in self.getjs.keys():
            self.var.set((self.getjs['0'] + self.getjs['1']))
        else:
            self.var.set((self.getjs['0'] + '省份:空'))

#类实例化 
three=ipchecktest()

#模块单独执行的时候，把下面的井号去掉即可
#three.windowsthree()